package com.lanmaoly.web.server.controller;

import com.lanmaoly.web.server.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片上传
 *
 * @author Administrator
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "upload")
public class FileController {

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "image")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        log.info("file image upload size:[{}] name:[{}] filename:[{}]",
                file.getSize(), file.getName(), originalFilename);
//        String originalFilenameFolder = GenerateOrderNum.generate(null) + originalFilename;
        String originalFilenameFolder = originalFilename;
        log.info("generate filename folder [{}]", originalFilenameFolder);
        String imagePath = request.getServletContext().getRealPath("/image/");
        String p = StringUtils.replace(imagePath, "\\", "/");
        String descDirNames = StringUtils.join(StringUtils.split(p, "/"), "/");
        log.info("descDirNames :{}", descDirNames);
        log.info("imagePath :{}", imagePath);
        // 两者都可以
        File descDir = new File(descDirNames);
//        File descDir = new File(imagePath);
        if (!descDir.exists()) {
            boolean mkdirs = descDir.mkdirs();
        }
        FileOutputStream ops = new FileOutputStream(descDirNames + File.separator + originalFilenameFolder);
        ops.write(file.getBytes());
        ops.flush();
        ops.close();
        return Result.success(originalFilenameFolder);
    }

}